<template>
  <div class="User">
    <div class="information">
      <div class="user_info">
        <h2>Information</h2>
        <div class="info_body">
          <div class="avatar">
            <img v-if="this.$store.getters.getAvatar" :src="this.$store.getters.getAvatar" alt="avatars" @click="history_avatars=true"
                 class="avatar">
            <!--      <el-button @click="tt"></el-button>-->

            <el-popover v-model="history_avatars">
              <el-upload
                  v-show="userdata.userid = this.$store.getters.getId()"
                  class="avatar-uploader"
                  action="http://10.21.119.242:8764/info/uploadAvatar"
                  :accept="'image/*'"
                  :headers="{Authorization: $store.getters.getToken}"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess">
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <div v-for="avatar in avatars" v-bind:key="avatar" class="history_avatars">
                <img :src=avatar alt=avatar @click="set_avatar(avatar)">
              </div>
            </el-popover>
          </div>
          <div style="display: flex; flex-direction: column; justify-content: space-around;">
            <el-row>username: {{ userdata.username }}</el-row>
            <el-row>email: {{ userdata.email }}</el-row>
          </div>
        </div>
      </div>


      <div class="friends">
        <h2>Friends</h2>
        <el-table
            :data="FriendsData"
            :header-cell-style="{background:'#696969',borderColor:'#CECECE',textAlign:'center'}"
            :cell-style="{background:'#696969',borderColor:'#CECECE',textAlign:'center', color:'#FFFFFF'}">
          <el-table-column label="" prop="face">
            <template slot-scope="scope">
              <img :src="scope.row.face" height="40" width="40">
            </template>
          </el-table-column>
          <el-table-column label="用户名" prop="name"></el-table-column>
        </el-table>


      </div>
    </div>

    <h2>My depository</h2>
    <div class="depository">
      <el-row
          v-for="game in GamesData" :key="game" :offset="index > 1 ? 3 : 0">
        <div class="game">
          <el-card>
            <img :src="game.img" class="image" width="120" height="90">
            <p style="color: #000000;">{{ game.name }}</p>
          </el-card>
        </div>
      </el-row>
    </div>
  </div>
</template>

<style scoped>
* {
  text-align: center;
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  color: white;
}

.information {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}

.friends {
  width: 20%;
}

.depository {
  background-color: #696969;
  padding: 10px;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.info_body {
  background-color: #696969;
  display: flex;
  flex-direction: row;
}

.game {
  padding: 10px;
  margin: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  background-color: black;
}
</style>

<script>
import {mapActions} from "vuex";
import baseUrl from "@/api/baseUrl";
import {getHistoryAvatar, getUserInfoById} from "@/api/user";

export default {
  watch: {

  },
  data() {
    return {
      postUrl: baseUrl + "info/uploadAvatar",
      history_avatars: false,
      avatars: {},
      FriendsData: [
        {
          face: require("@/assets/avatars/avatar1.png"),
          name: "嘤骑士",
          condition: "1"
        },
        {
          face: require("@/assets/avatars/avatar2.jpg"),
          name: "dust",
          condition: "2"
        },],
      GamesData: [
        {
          img: require("@/assets/1.jpg"),
          name: "game"
        },
        {
          img: require("@/assets/4.jpg"),
          name: "game"
        },
        {
          img: require("@/assets/5.jpg"),
          name: "game"
        },
      ],
      imgsrc: require("@/assets/1.jpg"),
      userdata:
          {
            userid: '',
            username: "Guest",
            email: "123@123.com"
          }
    }
  },
  created() {
    // 获取浏览器localStorage，判断用户曾经登录过
    // console.log(localStorage.getItem("token"))
    if (this.$route.query.username != null) {
      new Promise((resolve, reject) => {
        getUserInfoById(this.$store.getters.getToken(), this.$route.params.id)
      }).then(response => {
        let code = response.data.code;
        if (code == 200) {
          console.log('success');
        }
      })
    }
    if (this.$route.params.id != null) {
      new Promise((resolve, reject) => {
        getUserInfoById(this.$store.getters.getToken(), this.$route.params.id)
      }).then(response => {
        let code = response.code;
        if (code == 200) {
          console.log('success');
          this.userdata = response.data;
        }
      })
    } else {
      if (localStorage.getItem("token")) {
        // 如果token有效，则确认登录状态
        this.$store.dispatch("tokenVerify", localStorage.getItem("token")).then(response => {
          let code = response.data.code;
          if (code == 401) {
            this.setToken("");
            this.setUser("");
          } else {
            this.$store.dispatch("getUserInfo", localStorage.getItem("token")).then(response => {
              let code = response.data.code;
              if (code == 200) {
                console.log(response.data.userInfo)
                this.setBalance(response.data.userInfo.balance);
                this.setUsername(response.data.userInfo.username);
                this.setAvatar(baseUrl + response.data.userInfo.avatar.slice(1));
                console.log(this.$store.getters.getAvatar)
              }
            })
          }
        })
      } else {
        // this.$router.back()
      }
    }
  },
  methods: {
    ...mapActions(["setUser", "setAvatar", "setBalance", "setUsername"]),
    request_history_avatars() {
      new Promise((resolve, reject) => { //封装一个 Promise
        getHistoryAvatar(this.$store.getters.getToken).then(response => { //使用 user 接口进行网络请求
          resolve(response) //将结果封装进 Promise
        }).catch(error => {
          reject(error)
        })
      }).then(response => {
        let code = response.data.code
        if (code == 200) {
          let idx = 0;
          for (const path in response.data.path) {
            this.$set(this.avatars, idx, path)
            idx++;
          }
        }
      })
    },
    set_avatar(avatar) {
      if (avatar == "") {
        // this.uploadImg();
      }
      // console.log(avatar)
      this.setAvatar(avatar);
      this.history_avatars = false
    },
    handleAvatarSuccess(res, file) {
      // res表示后端的返回值，其中应包含文件上传后的url路径
      console.log(res);
      let avatar = res.data.avatar;
      // file表示这个上传文件本身
      console.log(file);
      this.setAvatar(baseUrl + avatar);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return true;
      // return isJPG && isLt2M;
    }
  },
}
</script>
